<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 6/25/17
 * Time: 5:37 PM
 */
declare(strict_types=1);


namespace wshore\core;

use Closure;
use wshore\Component;

final class Cache extends Component
{
    protected $_config = [
        WS_ADAPTER_CLASS => [
            'redis' => '\\wshore\\core\\cache\\Redis',
            'file' => '\\wshore\\core\\cache\\File',
            'memcached' => '\\wshore\\core\\cache\\Memcached',
        ],
        WS_ADAPTER_CONFIG => [
            'redis' => [
            ],
            'file' => [
            ],
            'memcached' => [
                'default' => [
                    'host' => '127.0.0.1',
                    'port' => 11211,
                    'weight' => 1
                ],
            ],
        ],
    ];

    /**
     * 获取缓存
     * @param string $name
     * @param Closure|mixed $replace 如果是一个闭包，则值不存在时获取并设置缓存
     * @param int $expire Closure返回值的缓存期
     * @return mixed
     */
    public function get(string $name, $replace = null, int $expire = WS_ONE_HOUR)
    {
        if ($replace instanceof Closure) {
            $value = $this->_adapter->get($name, null);
            if (null === $value) {
                $this->_adapter->set($name, $value = $replace(), $expire);
            }
        } else {
            $value = $this->_adapter->get($name, $replace);
        }
        return $value;
    }

}